package com.zs4sdk.activity;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.zs4sdk.activity.resetPassword.Zs4GameResetPasswordActivity;
import com.zs4sdk.common.Extra;
import com.common.library.data.CommonEventHandler.ResultHandlerInEvent;
import com.common.library.data.CommonHandle;
import com.common.library.data.CommonHandle.HandleMessage;
import com.common.library.data.EventHandler2Get;
import com.common.library.entity.JSONResultEntity;
import com.zs4sdk.entity.LoginJSONResultEntity;
import com.common.library.util.ActivityHelper;
import com.common.library.util.EncryptHelper;
import com.common.library.util.HandlerUtil;
import com.common.library.util.Helper;
import com.common.library.util.InputMethodeUtil;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;
import com.common.library.widget.SDKGameClearEditText;

/**
 * function: 找回密码
 *
 * @ author: aXiBa
 */
public class Zs4GameRetrievePasswordActivityBase extends Zs4GameBaseActivity implements OnClickListener {

    public static final String TAG = Zs4GameRetrievePasswordActivityBase.class.getSimpleName();

    private String mBlackColor = "#D5D5D5";

    private MyCount mSendMessageTimer;

    // 手机找回的提示
    private TextView sdkVerifyPhoneTipTextView;
    // 手机号码输入框
    private SDKGameClearEditText mAccountPhoneView;
    // 手机验证码输入框
    private SDKGameClearEditText mPhoneVerifyCodeView;
    // 请求手机验证码的按钮
    private Button mRequestVerifyCodeView;
    // 确认并提交
    private Button enSureAndSubmitButton;

    private int  titleType = 0;

    protected String phoneNumb = "";
    String phoneNumbFromAct = "";
    protected Class<?> cls = Zs4GameResetPasswordActivity.class;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyContentView();
        init();
    }
    protected void setMyContentView(){
        setContentView(ActivityHelper.getLayoutResId("zs4gamelayout_act_retrieve_password"));
        getParams();
        initReferences();
    }
    protected void initView(){
        setTopTitle(ActivityHelper.getStringResId("zs4gamestring_title_reset_password"));

//

        setViewClickEvent(this, ActivityHelper.getIdResId("zs4gameviewid_mMessageBtn_act_retrieve_textmessage"),
                ActivityHelper.getIdResId("zs4gameviewid_mSubmitView_act_retrieve_password"));
    }
    @Override
    protected void init() {
        super.init();
        initView();
    }


    protected String getPhoneNumb(){
        return  mAccountPhoneView.getText().toString().trim();
    }
    /**
     * 提交手机找回密码
     */
    private void confirmPhone() {

        InputMethodeUtil.closeInputMethod(this);
        if (NetworkHelper.isNetworkAvailable(Zs4GameRetrievePasswordActivityBase.this)) {
            phoneNumb =getPhoneNumb();
            String verifycode = mPhoneVerifyCodeView.getText().toString().trim();

            if(phoneNumb.equals("")||verifycode.equals("")){
                return;
            }
            if (!Helper.checkMobile(phoneNumb)) {
                sdkVerifyPhoneTipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_num_format"));
            } else {
//                Log.i("这里进行请求手机找回密码", "");
                httpGetSDKForgetCodeCommandPhone(phoneNumb, verifycode);
            }
        } else {
            sdkVerifyPhoneTipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
        }
    }


    /*定义一个倒计时的内部类*/
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            // 还原btn按钮
            mRequestVerifyCodeView.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_red_5_bg"));
            mRequestVerifyCodeView.setClickable(true);
            mRequestVerifyCodeView.setText(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_btn_send_message_verify")));

        }

        @Override
        public void onTick(long millisUntilFinished) {
            mRequestVerifyCodeView.setText("重新发送" + millisUntilFinished / 1000 + "秒");
            // 设置btn样式
            mRequestVerifyCodeView.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_gray_5_bg"));
            // 设置不可点击
            mRequestVerifyCodeView.setClickable(false);
        }
    }


    /**
     * 获取验证码
     */
    private void getVerifyCode(String sendmode) {


        phoneNumb = getPhoneNumb();


        // 判断手机号格式：开头是1且为11位
        if (phoneNumb.equals("")) {
//            sdkVerifyPhoneTipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_num_format"));
            return;
        }

        // 判断手机号格式：开头是1且为11位
        if (!Helper.checkMobile(phoneNumb)) {
            sdkVerifyPhoneTipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_num_format"));
            return;
        }

        if (NetworkHelper.isNetworkAvailable(this)) {
            // 开启计时器
            if (sendmode == Extra.VERIFYTYPE.VERIFYTYPE_TEXTMESSAGE) {
                mSendMessageTimer = new MyCount(Extra.SDKGAMESTRS.GET_AGAIN, 1000);
                mSendMessageTimer.start();
            }

            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("mobile", EncryptHelper.encryptByAES(phoneNumb)));
//            paramList.add(new BasicNameValuePair("sendmode", sendmode));

            new EventHandler2Get(
                    Extra.URL.PHONEVERIFYCODE,
                    paramList,
                    ParamsHelper.getUserAgent1(), new ResultHandlerInEvent() {

                @Override
                public void doResultHanler(JSONObject result) throws JSONException {

                    Message msg = myHandle.obtainMessage();

                    msg.what = Extra.MessageKey.REQUEST_VERIFY_SUCCESS;
                    msg.obj = result;

                    Bundle bundle = new Bundle();
//
                    msg.setData(bundle);

                    // 发送消息
                    myHandle.sendMessage(msg);

                }

                @Override
                public void doExceptionHandler() {

                }
            });
        } else {
            sdkVerifyPhoneTipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
        }
    }

    /**
     * 请求手机找回密码（117）
     *
     * @param mobile
     * @param verifycode
     */
    private void httpGetSDKForgetCodeCommandPhone(final String mobile, final String verifycode) {

        HandlerUtil.sendMessage(myHandle, Extra.MessageKey.SHOWPROCESS);

        ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
        paramList.add(new BasicNameValuePair("mobile", EncryptHelper.encryptByAES(mobile)));
        paramList.add(new BasicNameValuePair("verifycode", EncryptHelper.encryptByAES(verifycode)));
        paramList.add(new BasicNameValuePair("checkuser", Extra.REQUESTCODE.CHECK_PHONE_USER));

        new EventHandler2Get(
                Extra.URL.VERIFY_PHONE_CODE,
                paramList,
                ParamsHelper.getUserAgent1(),
                new ResultHandlerInEvent() {

                    @Override
                    public void doResultHanler(JSONObject result) throws JSONException {

                        HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);

                        Message msg = myHandle.obtainMessage();

                        msg.what = Extra.MessageKey.REQUEST_SUCCESS;
//                        msg.what = 111;
                        msg.obj = result;

                        Bundle bundle = new Bundle();
                        bundle.putString("param1", mobile);

                        msg.setData(bundle);

                        // 发送消息
                        myHandle.sendMessage(msg);

                    }

                    @Override
                    public void doExceptionHandler() {
                        HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                    }
                });


    }


    CommonHandle myHandle = new CommonHandle(Zs4GameRetrievePasswordActivityBase.this, new HandleMessage() {

        @Override
        public void doHandleMessage(Message msg) {

            if (Extra.MessageKey.REQUEST_VERIFY_SUCCESS == msg.what) {

                LoginJSONResultEntity entity = new LoginJSONResultEntity((JSONObject) msg.obj);
                if (entity.isSuccess()) {
                } else {
                    sdkVerifyPhoneTipTextView.setText(entity.getDesc());
                }
            }
            if (Extra.MessageKey.REQUEST_SUCCESS == msg.what) {
                JSONResultEntity entity = new JSONResultEntity((JSONObject) msg.obj);
                if (entity.getResult() == Extra.RESULTCODE.SUCCESS) {
                    Bundle bundle = msg.getData();
                    String mobile = bundle.getString("param1");
                    Intent intent = new Intent(Zs4GameRetrievePasswordActivityBase.this, cls);
                    intent.putExtra("mobile", mobile);
                    intent.putExtra(Extra.INTENTKEY.TITLE,titleType);
                    startActivity(intent);
                    finish();
                } else {
                    sdkVerifyPhoneTipTextView.setText(entity.getDesc());
                }

            }
            if (111 == msg.what) {

                    Bundle bundle = msg.getData();
                    String mobile = bundle.getString("param1");
                    Intent intent = new Intent(Zs4GameRetrievePasswordActivityBase.this, Zs4GameResetPasswordActivity.class);
                    intent.putExtra("mobile", mobile);
                    intent.putExtra(Extra.INTENTKEY.TITLE,titleType);
                    startActivity(intent);
                    finish();
            }

        }
    });


    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (ActivityHelper.getIdResId("zs4gameviewid_mSubmitView_act_retrieve_password") == v.getId()) {

            confirmPhone();

        }// 获取短信验证码
        else if (v.getId() == ActivityHelper.getIdResId("zs4gameviewid_mMessageBtn_act_retrieve_textmessage")) {
            getVerifyCode(Extra.VERIFYTYPE.VERIFYTYPE_TEXTMESSAGE);
        }
    }

    // 获得参数
    private void getParams() {

//        Intent intent = this.getIntent();
//
//        Bundle bundle = intent.getExtras();
//        if (Helper.isNotNull(bundle)) {
//            titleType = bundle.getInt(Extra.INTENTKEY.TITLE);
//            if(bundle.containsKey(Extra.INTENTKEY.PHONE_NUMBER)){
//                phoneNumbFromAct = bundle.getString(Extra.INTENTKEY.PHONE_NUMBER);
//            }
//        }

    }

    // 设置界面
    protected void initReferences() {

        //提示
        sdkVerifyPhoneTipTextView = findView(TextView.class, ActivityHelper.getIdResId("zs4gameviewid_act_txv_retrieve_pwd_tip"));
        //手机号
        mAccountPhoneView = findView(SDKGameClearEditText.class, ActivityHelper.getIdResId("zs4gameviewid_mAccountView_act_retrieve_password_phone"));
        //验证码
        mPhoneVerifyCodeView = findView(SDKGameClearEditText.class, ActivityHelper.getIdResId("zs4gameviewid_mMessageView_act_retrieve_textmessage"));
        //获取验证码
        mRequestVerifyCodeView = findView(Button.class, ActivityHelper.getIdResId("zs4gameviewid_mMessageBtn_act_retrieve_textmessage"));
        //确认并提交
        enSureAndSubmitButton = findView(Button.class, ActivityHelper.getIdResId("zs4gameviewid_mSubmitView_act_retrieve_password"));

    }

    @Override
    protected int getLeftBtnType() {
        return TYPE_LEFTBTN_BACK;
    }

    @Override
    protected int getRightBtnType() {
        return TYPE_RIGHTBTN_INVISIBLE;
    }
}
